package org.dk.controller;

import com.alibaba.fastjson.JSON;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dk.domain.DataResult;
import org.dk.em.DataResultEnum;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URISyntaxException;

@RequestMapping("clientController")
@Controller
public class ClientController {
    @RequestMapping("addressClient")
    @ResponseBody
    public DataResult addressClient(){
        CloseableHttpResponse response = null;
        String content = null;

        String city = "北京";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建URIBuilder http://wthrcdn.etouch.cn/weather_mini?city=沈阳
        try {
            URIBuilder uriBuilder = new URIBuilder("http://wthrcdn.etouch.cn/weather_mini");
            uriBuilder.setParameter("city",city);
            //2.创建一个Get请求,设置url访问地址
             HttpGet httpGet = new HttpGet(uriBuilder.build());
            response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == 200){
                content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println("响应状态为:"+response.getStatusLine());
                System.out.println("响应内容为:"+ content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //5.释放资源
                if(response != null){
                    response.close();
                }if(httpClient != null){
                    httpClient.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return DataResult.buildDataResult(DataResultEnum.SUCCESS).setData(content);
    }
}
